package cn.cai.pethome.pet.service.impl;

import cn.cai.pethome.pet.domain.PetType;
import cn.cai.pethome.pet.mapper.PetTypeMapper;
import cn.cai.pethome.pet.service.IPetTypeService;
import cn.cai.pethome.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaocai
 * @since 2022-09-10
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {


    @Autowired
    private PetTypeMapper petTypeMapper;

    /**
     * 查询宠物类别树：级联框
     * @return
     */
    @Override
    public List<PetType> getTree() {
        //查询所有
        List<PetType> petTypes = petTypeMapper.findAll();

        //创建一个map集合
        Map<Long,PetType> map = new HashMap<>();
        petTypes.forEach(petType -> map.put(petType.getId(),petType));

        //封装一级类别集合
        List<PetType> firstLevelTypes = new ArrayList<>();
        for (PetType petType : petTypes) {
            if (petType.getPid() == null){
                firstLevelTypes.add(petType);//一级的
            }else {
                PetType parent = map.get(petType.getPid());
                parent.getChildren().add(petType);
            }
        }

        return firstLevelTypes;
    }

    /**
     * 查询所有的一级宠物类别：新增和修改宠物类别的时候使用  下拉框
     * @return
     */
    @Override
    public List<PetType> getFirstLevelType() {
        //查询所有
        List<PetType> petTypes = petTypeMapper.findAll();

        return petTypes.stream().filter(petType -> petType.getPid() == null).collect(Collectors.toList());
    }
}
